import React, { memo, useEffect, useState } from 'react';
import { connect } from 'umi';
import { formatMessage } from 'umi';
import { isEmpty } from 'lodash';
import { history } from 'umi'
import classNames from 'classnames';
import {
    Spin,
    Card,
    Tree,
    Empty,
    Checkbox,
    Button,
    message,
    Modal,
    Icon,
    Typography,
    Popover,
    Steps,
    Dropdown,
    Menu,
    Select
} from 'antd'

import { withRoutePage } from '@/utils/enhanceUtils';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { colors } from '@/theme';
import { BottomAction } from '@/components';
import pageTabUtil from '@/utils/pageTabUtil';
import If from '@/components/If';
import DateFormatter from '@/components/DateFormatter';
import { defaultFormatResult } from '@/hooks';

import {
    queryCompanyList,
    queryCompanyTemplateList,
    querySalaryLibYearList,
    onUseTemplate,
    onUseMultipleTemplate
} from '@/services/salaryManage/salaryCalculate';
import salaryManageStyle from '@/pages/SalaryManage/salaryManage.less';
import { goToProcessDetail } from '@/pages/SalaryManage/utils/pageNavigateUtil';
import StatusTag from '@/pages/SalaryManage/components/ProcessStatus';
import { getCurrentCompanyCode, obtainDictMap, pageTabProps } from '@/pages/SalaryManage/utils';
import tabMessageUtil from '@/pages/SalaryManage/utils/tabMessageUtil';

import styles from './index.less';
import { MONTHList } from '../../utils/staticList';

const { Text } = Typography;
const { Step } = Steps;

const { TreeNode, DirectoryTree } = Tree;
import LogoImg from '@/assets/logo2.png';

const SALARY_OBJECT_OPTIONS = 'salaryObjectOptions';
const DICT_NAME_LIST = [SALARY_OBJECT_OPTIONS];

// 将数据拉平
const flatten = dataList =>
    [...dataList].reduce((result, current) => {
        let rel = [...result];
        rel.push(current);
        if (current.children && current.children.length > 0) {
            rel = rel.concat(flatten(current.children));
        }
        return rel;
    }, []);

// 多选
const isMultipleMode = selectType => selectType === 'multiple';
// 单选
const isSingleMode = selectType => selectType === 'single';

// 获取模板年份
const useLibYearList = orgCode => {
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState([]);

    useEffect(() => {
        if (orgCode) {
            setLoading(true);
            querySalaryLibYearList(orgCode)
                .then(defaultFormatResult.formatResult)
                .then(res => setData(res))
                .finally(() => setLoading(false))
        }
    }, [orgCode]);

    return [loading, data];
}

const SalaryItemList = memo(({ data = [] }) => {
    const [salaryObjectEnum, setSalaryObjectEnum] = useState({});

    useEffect(() => {
        obtainDictMap(DICT_NAME_LIST).then(enumMap => {
            setSalaryObjectEnum(enumMap[SALARY_OBJECT_OPTIONS]);
        });
    }, []);

    return (
        <div className={styles.salaryItemList}>
            {data.map(item => (
                <Dropdown
                    key={item.id}
                    trigger={['hover']}
                    getPopupContainer={triggerNode => triggerNode.parentNode}
                    overlay={() => (
                        <Menu className={styles.dropdownBox}>
                            <Menu.Item className={styles.dropdownItem}>
                                <span className={styles.dropdownLabel}>全称：</span>
                                <span>
                                    {item.parentTitle}
                                    {item.title}
                                </span>
                            </Menu.Item>
                            <Menu.Item className={styles.dropdownItem}>
                                <span className={styles.dropdownLabel}>
                                    {(item.formulaFlow && '审批流：') ||
                                        (item.formulaFunc && '公式：') ||
                                        (item.staffInfoName && '取值关联字段：')}
                                </span>
                                <span>{item.formulaFlow || item.formulaFunc || item.staffInfoName}</span>
                            </Menu.Item>
                            <Menu.Item className={styles.dropdownItem}>
                                <span className={styles.dropdownLabel}>对象：</span>
                                <span>{salaryObjectEnum[item.salaryObject]}</span>
                            </Menu.Item>
                        </Menu>
                    )}
                    placement="topCenter"
                    mouseEnterDelay={0.3}
                >
                    <div className={styles.salaryItemLabelWrap} key={item.id}>
                        <span className={styles.salaryItemLabel}>{item.parentTitle}</span>
                        <span className={styles.salaryItemLabel}>{item.title}</span>
                    </div>
                </Dropdown>
            ))}
        </div>
    );
});
const TemplateLibrary = ({ location }) => {
    const [treeLoading, setTreeLoading] = useState(false);
    const [templateLoading, setTemplateLoading] = useState(false);
    const [operating, setOperating] = useState(false);
    const [companyList, setCompanyList] = useState([]);
    const [flatCompanyList, setFlatCompanyList] = useState([]);
    const [currentCompanyCode, setCurrentCompanyCode] = useState('');
    const [currentQuote, setCurrentQuote] = useState(false);
    const [monthDataList, setMonthDataList] = useState([]);
    const [selectKeys, setSelectKeys] = useState([]);
    const [selectType, setSelectType] = useState('');
    const [allChecked, setAllChecked] = useState(false);
    const [allIndeterminate, setAllIndeterminate] = useState(false);
    const [stepList, setStepList] = useState([]);
    const [pageModel, setPageModel] = useState({});
    const [, yearList] = useLibYearList(currentCompanyCode);
    const [currentSelectYear, setCurrentYear] = useState(null);

    const organizationCode = location.query.targetcode || getCurrentCompanyCode();
    const getCompanyList = async () => {
        try {
            setTreeLoading(true);
            const { code, data = [] } = await queryCompanyList(organizationCode);
            if (code === 10000) {
                console.log('公司列表数据', data);
                setCompanyList(data);
                if (data.length && data[0].children.length) {
                    // 将数据拉平
                    setFlatCompanyList(flatten(data));
                    const currentCompany = data[0].children[0];
                    setCurrentCompanyCode(currentCompany.organizationCode);
                    setCurrentQuote(currentCompany.quote);
                }
            }
            setTreeLoading(false);
        } catch (e) {
            console.log(e);
            setTreeLoading(false);
        }
    };
    const getCompanyTemplateList = async () => {
        if (!currentSelectYear) {
            return;
        }
        try {
            setTemplateLoading(true);
            const { code, data, msg } = await queryCompanyTemplateList(
                currentCompanyCode, organizationCode, currentSelectYear
            );
            if (code === 10000) {
                const { templateList = [], processVOs = [] } = data;

                // 1.处理发放流程信息
                setStepList(processVOs);

                // 2.处理月份列表模板数据
                console.log('月份列表数据', templateList);
                const monthKeys = Object.keys(templateList);
                const monthSalaryListArr = monthKeys.map(month => ({
                    month,
                    name: MONTHList[month - 1].monthName,
                    ...templateList[month],
                    disabled:
                        !templateList[month].usedAddSalaryItems.length &&
                        !templateList[month].usedLessSalaryItems.length
                }));
                setMonthDataList(monthSalaryListArr);

                // 3.存储页面其它要用到的信息
                const templateApproveInfo = {
                    processStatusAble: data.processStatusAble,
                    processStatus: data.processStatus,
                    months: data.months
                };
                setPageModel({
                    templateApproveInfo,
                    approveDetailAble: data.approveDetailAble,
                    processDefinitionId: data.processDefinitionId,
                    processInstanceId: data.processInstanceId,
                    quoteAble: data.quoteAble
                });
            } else {
                message.error(msg);
            }
            setTemplateLoading(false);
        } catch (e) {
            setTemplateLoading(false);
        }
    };
    const getCompany = key => (flatCompanyList || []).find(item => item.organizationCode === key);
    // 是否能使用
    const canQuote = monthData => currentQuote && pageModel.quoteAble && !monthData.disabled;
    // 获取所有全选数据
    const getAllEnabled = () => monthDataList.filter(monthData => canQuote(monthData));
    const hasChecked = targetId => !!selectKeys.find(val => val === targetId);
    const onSetTemplateSelectType = () => {
        if (!isEmpty(location.query)) {
            setSelectType(location.query.targetid ? 'single' : 'multiple');
        }
    };
    const onOperationUseTemplate = async (isSingle, monthData) => {
        try {
            const { targetid, targetcode, year: toYear } = location.query;
            setOperating(true);
            const { code, msg } = isSingle
                ? await onUseTemplate({
                    fromTemplateId: monthData.salaryTemplateId,
                    fromOrgCode: currentCompanyCode,
                    toOrgCode: targetcode,
                    toTemplateId: targetid
                })
                : await onUseMultipleTemplate({
                    fromOrgCode: currentCompanyCode,
                    toOrgCode: targetcode,
                    fromTemplateIds: selectKeys.join(','),
                    toYear
                });

            setOperating(false);
            if (code === 10000) {
                message.success('引用成功！');
                tabMessageUtil.noticeFromRefresh();
                history.push({
                    pathname: '/finance/salary/calculate/templatesetting/salarytemplate',
                    query: {
                        year: location.query.year,
                        month: location.query.month
                    },
                    state: {
                        tabRoute: true,
                        tabRefresh: true,
                        organizationCode: targetcode
                    }
                });
            } else {
                Modal.warning({
                    title: '无法引用',
                    icon: <Icon type="exclamation-circle" theme="filled" style={{ color: colors.orange }} />,
                    content: <Text type="secondary">{msg || '引用失败!'}</Text>,
                    okText: '我知道了'
                });
            }
        } catch (e) {
            setOperating(false);
            console.log(e);
        }
    };
    const onSetMulSelectKey = async (targetId, checked) => {
        const newSelectKeys = selectKeys.slice();
        if (checked) {
            newSelectKeys.push(targetId);
        } else {
            const index = newSelectKeys.indexOf(targetId);
            newSelectKeys.splice(index, 1);
        }
        setSelectKeys(newSelectKeys);
        setAllChecked(newSelectKeys.length && newSelectKeys.length === getAllEnabled().length);
        setAllIndeterminate(newSelectKeys.length > 0 && newSelectKeys.length < getAllEnabled().length);
    };
    const onSelectCompany = key => {
        console.log(key);
        if (key.length && key[0] !== currentCompanyCode) {
            setCurrentCompanyCode(key[0]);
            // 设置当时是否能引用
            setCurrentQuote(getCompany(key[0]).quote);
            setSelectKeys([]);
            setAllChecked(false);
            setAllIndeterminate(false);
        }
    };
    const renderTreeNode = (companyArr = [], isFirst = false) =>
        companyArr.map(company => (
            <TreeNode
                title={company.organizationName}
                key={company.organizationCode}
                selectable={!isFirst}
                icon={
                    isFirst ? (
                        <img src={LogoImg} alt="" className={styles.logoImg} />
                    ) : (
                        <i
                            className="icon iconfont iconlist_icon_company_default1"
                            style={{ fontSize: 16, height: '21px', lineHeight: '23px', marginRight: '6px' }}
                        />
                    )
                }
            >
                {renderTreeNode(company.children)}
            </TreeNode>
        ));

    useEffect(() => {
        getCompanyList();
        onSetTemplateSelectType();
    }, []);
    useEffect(() => {
        if (currentCompanyCode && currentSelectYear) {
            getCompanyTemplateList();
        }
    }, [currentCompanyCode, currentSelectYear]);

    useEffect(() => {
        if (yearList?.length > 0) {
            setCurrentYear(yearList[yearList.length - 1]);
        } else {
            setCurrentYear(undefined);
        }
    }, [yearList]);

    /**
     * 全选或取消全选
     * @param checked
     */
    const toggleAll = checked => {
        const allSalaryTemplateId = getAllEnabled().map(monthData => monthData.salaryTemplateId);

        setSelectKeys(checked ? allSalaryTemplateId : []);
        setAllChecked(checked);
        setAllIndeterminate(false);
    };

    /**
     * 取消
     */
    const goBack = () => {
        pageTabUtil.closeTab();
        history.push({
            pathname: '/finance/salary/calculate/templatesetting/salarytemplate',
            state: {
                tabRoute: true,
                tabRefresh: true
            }
        });
    };

    const actionFoot = (
        <If condition={isMultipleMode(selectType)}>
            <BottomAction>
                <Button onClick={goBack}>取消</Button>
                <Button
                    type="primary"
                    disabled={!selectKeys.length}
                    onClick={() => {
                        onOperationUseTemplate(false);
                    }}
                >
                    确认引用
                </Button>
            </BottomAction>
        </If>
    );

    return (
        <PageHeaderWrapper type="success">
            <Card
                title={
                    <>
                        模板库
                        <StatusTag templateInfo={pageModel.templateApproveInfo} style={{ marginLeft: '8px' }} />
                    </>
                }
                {...pageTabProps()}
            >
                <Spin spinning={operating}>
                    <div className={styles.container}>
                        <div className={styles.titleWrap}>
                            <div className={styles.leftTitleWrap}>
                                <If condition={isMultipleMode(selectType) || isSingleMode(selectType)}>
                                    <Text type="secondary" style={{ marginRight: '40px' }}>
                                        <Icon type="exclamation-circle" style={{ marginRight: 5 }} />
                                        <If condition={isMultipleMode(selectType)}>
                                            多选模式下，被勾选模板将按照月份对应引用覆盖
                                        </If>
                                        <If condition={isSingleMode(selectType)}>单选模式下，支持不同月份引用</If>
                                    </Text>
                                </If>
                                <If condition={!isMultipleMode(selectType) && !isSingleMode(selectType)}>
                                    <Text type="secondary" style={{ marginRight: '40px' }}>
                                        <Icon type="exclamation-circle" style={{ marginRight: 5 }} />
                                        模板库信息由对应公司实时同步
                                    </Text>
                                </If>
                            </div>
                            <div>
                                模板年份：
                                <Select
                                    placeholder="请选择年份"
                                    value={currentSelectYear || undefined}
                                    onChange={year => setCurrentYear(year)}
                                    className={salaryManageStyle.mr16}
                                    style={{ display: 'inline-block', width: '120px' }}
                                >
                                    {yearList?.map(item => <Select.Option key={item}>{item}</Select.Option>)}
                                </Select>
                                <Button
                                    type="link"
                                    onClick={() =>
                                        goToProcessDetail({
                                            processDefinitionId: pageModel.processDefinitionId,
                                            processInstanceId: pageModel.processInstanceId
                                        })
                                    }
                                    className={salaryManageStyle.linkBtn}
                                    disabled={!pageModel.approveDetailAble}
                                >
                                    查看审批详情
                                </Button>
                                <Popover
                                    placement="topLeft"
                                    arrowPointAtCenter
                                    content={
                                        <div
                                            style={{
                                                width: isMultipleMode(selectType)
                                                    ? 'calc(100vw - 500px)'
                                                    : 'calc(100vw - 370px)'
                                            }}
                                        >
                                            <If condition={stepList?.length > 0}>
                                                <Steps labelPlacement="vertical" className={styles.stepWrap}>
                                                    {stepList.map(item => {
                                                        if (item.enable && !item.hidden) {
                                                            return (
                                                                <Step
                                                                    key={item.index}
                                                                    title={item.title}
                                                                    status={item.fixed ? 'wait' : 'process'}
                                                                />
                                                            );
                                                        }
                                                        return null;
                                                    })}
                                                </Steps>
                                            </If>
                                            <If condition={!stepList || stepList.length === 0}>
                                                <Empty
                                                    image={Empty.PRESENTED_IMAGE_SIMPLE}
                                                    imageStyle={{ margin: '5px' }}
                                                    style={{ margin: 0 }}
                                                />
                                            </If>
                                        </div>
                                    }
                                    trigger={['hover']}
                                >
                                    <Button className={classNames(salaryManageStyle.iconBtn, salaryManageStyle.ml16)}>
                                        发放流程
                                        <Icon type="question-circle" />
                                    </Button>
                                </Popover>
                                <If condition={isMultipleMode(selectType)}>
                                    <Checkbox
                                        onChange={e => {
                                            toggleAll(e.target.checked);
                                        }}
                                        checked={allChecked}
                                        indeterminate={allIndeterminate}
                                        className={salaryManageStyle.ml16}
                                    >
                                        全选
                                    </Checkbox>
                                </If>
                            </div>
                        </div>
                        <div className={styles.mainContainer}>
                            <Spin spinning={treeLoading}>
                                <div className={styles.containerLeft}>
                                    <If condition={companyList.length && currentCompanyCode}>
                                        <DirectoryTree
                                            defaultExpandAll
                                            defaultSelectedKeys={[currentCompanyCode]}
                                            onSelect={onSelectCompany}
                                        >
                                            {renderTreeNode(companyList, true)}
                                        </DirectoryTree>
                                    </If>
                                </div>
                            </Spin>
                            <div className={styles.containerRight}>
                                <Spin spinning={templateLoading}>
                                    <div className={styles.monthContentList}>
                                        {monthDataList?.length > 0 ? (
                                            monthDataList.map(monthData => (
                                                <div className={styles.monthWrap} key={monthData.name}>
                                                    <div className={styles.monthHeader}>
                                                        <div className={styles.monthHeaderTop}>
                                                            <div className={styles.monthName}>
                                                                {monthData.name}
                                                                <Button
                                                                    className={classNames(
                                                                        salaryManageStyle.iconBtn,
                                                                        styles.monthTimePicker
                                                                    )}
                                                                    disabled
                                                                >
                                                                    <span className="pg-picker">
                                                                        <i
                                                                            className={classNames([
                                                                                'iconfont',
                                                                                'iconoa_menu_icon_attendance'
                                                                            ])}
                                                                        />
                                                                        <span className="pg-time">
                                                                            <DateFormatter
                                                                                value={monthData.generateDate}
                                                                                pattern="MM-DD"
                                                                                emptyMessage="MM-DD"
                                                                            />
                                                                        </span>
                                                                    </span>
                                                                    <span>生成薪资条</span>
                                                                </Button>
                                                            </div>

                                                            {selectType ? (
                                                                <div>
                                                                    {isSingleMode(selectType) ? (
                                                                        <Button
                                                                            className={styles.monthOperationBtn}
                                                                            type="primary"
                                                                            size="small"
                                                                            disabled={!canQuote(monthData)}
                                                                            onClick={() => {
                                                                                onOperationUseTemplate(true, monthData);
                                                                            }}
                                                                        >
                                                                            引用模板
                                                                        </Button>
                                                                    ) : (
                                                                        <Checkbox
                                                                            disabled={!canQuote(monthData)}
                                                                            onChange={e => {
                                                                                onSetMulSelectKey(
                                                                                    monthData.salaryTemplateId,
                                                                                    e.target.checked
                                                                                );
                                                                            }}
                                                                            checked={hasChecked(
                                                                                monthData.salaryTemplateId
                                                                            )}
                                                                        />
                                                                    )}
                                                                </div>
                                                            ) : null}
                                                        </div>
                                                        <div className={styles.monthHeaderBottom}>
                                                            <span className={styles.createNameLabel}>创建人：</span>
                                                            <span className={styles.createNameText}>
                                                                {monthData.createName}
                                                            </span>
                                                            <span className={styles.line} />
                                                            <span>{monthData.createTime}</span>
                                                        </div>
                                                    </div>
                                                    {!monthData.disabled ? (
                                                        <div className={styles.monthContent}>
                                                            <div>
                                                                <div className={styles.itemTitle}>
                                                                    <i
                                                                        className="icon iconfont iconsalary_add_icon"
                                                                        style={{
                                                                            fontSize: 14,
                                                                            color: 'rgba(79, 216, 123, 1)'
                                                                        }}
                                                                    />{' '}
                                                                    <span className={styles.itemTitleText}>
                                                                        {formatMessage({
                                                                            id:
                                                                            'templateSetting.salaryTemplate.salaryAddItem'
                                                                        })}
                                                                    </span>
                                                                </div>
                                                                <SalaryItemList data={monthData.usedAddSalaryItems} />
                                                            </div>
                                                            <div>
                                                                <div className={styles.itemTitle}>
                                                                    <i
                                                                        className="icon iconfont iconsalary_minus_icon"
                                                                        style={{
                                                                            fontSize: 14,
                                                                            color: 'rgba(255, 121, 67, 1)'
                                                                        }}
                                                                    />{' '}
                                                                    <span className={styles.itemTitleText}>
                                                                        {formatMessage({
                                                                            id:
                                                                            'templateSetting.salaryTemplate.salaryReduceItem'
                                                                        })}
                                                                    </span>
                                                                </div>
                                                                <SalaryItemList data={monthData.usedLessSalaryItems} />
                                                            </div>
                                                        </div>
                                                    ) : (
                                                        <Empty
                                                            className={styles.monthEmpty}
                                                            image={Empty.PRESENTED_IMAGE_SIMPLE}
                                                            description={<span>本月薪资还未配置哦 ~ </span>}
                                                        />
                                                    )}
                                                </div>
                                            ))
                                        ) : (
                                            <div
                                                style={{
                                                    marginTop: 100,
                                                    marginLeft: 'auto',
                                                    marginRight: 'auto'
                                                }}
                                            >
                                                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                                            </div>
                                        )}
                                    </div>
                                </Spin>
                            </div>
                        </div>
                    </div>
                    {actionFoot}
                </Spin>
            </Card>
        </PageHeaderWrapper>
    );
};
export default withRoutePage(
    connect(({ user }) => ({
        currentOrgCode: getCurrentCompanyCode(user.currentUser)
    }))(TemplateLibrary)
);
